local NetWorkManager = class("NetWorkManager")
local Signal = require("event.Signal")

function NetWorkManager:ctor()
    self._signalMaps = {}
    self._curSignalId = nil
    self._globalSignalId = 1
    self._cacheSlots = {}
end

function NetWorkManager:add(id, listener, priority)
    return self:registerListener(id, listener, false, priority or 0)
end

function NetWorkManager:addOnce(id, listener, priority)
    return self:registerListener(id, listener, true, priority or 0)
end

function NetWorkManager:registerListener(id, listener, once, priority)
    local signal = self._signalMaps[id]
    if not signal then
        signal = Signal.new()
        self._signalMaps[id] = signal
    end
    local slot = signal:registerListener(listener, priority, once)
    if self._curSignalId then
        assert(self._cacheSlots[self._curSignalId], "not cache")
        table.insert(self._cacheSlots[self._curSignalId], slot)
    end
    return slot
end

function NetWorkManager:beginCache()
    self._curSignalId = self._globalSignalId
    self._globalSignalId = self._globalSignalId + 1
    self._cacheSlots[self._curSignalId] = {}
end

function NetWorkManager:endCache()
    self._curSignalId = nil
end

function NetWorkManager:removeCache(id)
    local list = self._cacheSlots[id] or {}
    for i = 1, #list do
        list[i]:remove()
    end
    self._cacheSlots[id] = nil
end

function NetWorkManager:dispatch(id, ...)
    local signal = self._signalMaps[id]
    if signal then
        signal:dispatch(id, ...)
    end
end

function NetWorkManager:send(id, message)
    G_SocketManager:sendMessage(id, message)
end

return NetWorkManager
